<template>
  <a-spin :spinning="confirmLoading">

    <a-tabs :activeKey="customActiveKey" :tabBarStyle="{ textAlign: 'left', borderBottom: 'unset' }"  @change="handleTabClick">
      <a-tab-pane key="tab1" tab="Basic"  >
        <j-form-container :disabled="formDisabled" >
          <a-form-model ref="form" :model="model" :layout="form.layout" :rules="validatorRules" slot="detail">
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="First Name"   :wrapperCol="wrapperCol" prop="firstName">
                  <a-input v-model="model.firstName" @change="handFirstNameChange" placeholder=""  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="Last Name"   :wrapperCol="wrapperCol" prop="lastName">
                  <a-input v-model="model.lastName" @change="handLastNameChange" placeholder=""  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="Chinese Name/WeChat Name" prop="chineseName"  :wrapperCol="wrapperCol" >
                  <a-input v-model="model.chineseName" placeholder=""  ></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="Grade"   :wrapperCol="wrapperCol" prop="grade">
                  <j-dict-select-tag type="list" v-model="model.grade" dictCode="grade" placeholder="" />
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="School"   :wrapperCol="wrapperCol" prop="school">
                  <a-input v-model="model.school" @change="handSchoolChange" placeholder=""  ></a-input>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="Email"  :wrapperCol="wrapperCol" prop="email">
                  <a-input v-model="model.email" placeholder=""  ></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row>

              <a-col :span="8">
                <a-form-model-item label="Mobile Phone"   :wrapperCol="wrapperCol" prop="mobileNumber">
                  <a-input style="width: 100%" v-model="model.mobileNumber">
                    <a-select
                      slot="addonBefore"
                      v-model="model.mobilePrefix"
                      style="width: 70px"
                    >
                      <a-select-option value="86">
                        +86
                      </a-select-option>
                      <a-select-option value="1">
                        +1
                      </a-select-option>
                    </a-select>
                  </a-input>
                </a-form-model-item>
              </a-col>

              <!--<a-col :span="8">
                <a-form-model-item label="Phone"  style="margin-bottom:0;" :wrapperCol="wrapperCol" prop="phone">
                    <a-form-model-item style="margin-bottom:0;"  prop="phonePrefix">
                          <a-input-group compact>
                            <a-input
                              v-model="model.phonePrefix"
                              placeholder=""
                              :max-length="3"
                              @change="onPhonePrefixChange"
                              style="width: 30%"
                            />
                            <a-input
                              ref="stPhone"
                              v-model="model.phone"
                              placeholder=""
                              :max-length="7"
                              style="width: 70%"
                            />
                          </a-input-group>
                    </a-form-model-item>
                </a-form-model-item>
              </a-col>-->

              <a-col :span="8">
                <a-form-model-item label="School Type"   :wrapperCol="wrapperCol" prop="schoolType">
                  <j-dict-select-tag type="list" v-model="model.schoolType" dictCode="school" placeholder="" />
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="Postal Code"   :wrapperCol="wrapperCol" prop="postalCode">
                  <a-input v-model="model.postalCode" placeholder=""  ></a-input>
                </a-form-model-item>
              </a-col>


            </a-row>
            <a-row>


              <a-col :span="8">
                <a-form-model-item label="Region" :wrapperCol="wrapperCol" prop="region">
                  <j-dict-select-tag type="list"  @change="handChangeRegion" :triggerChange="true" v-model="model.region" dictCode="regionList" placeholder="" />
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="City"   :wrapperCol="wrapperCol" prop="city">
                  <j-dict-select-tag type="list" v-model="model.city" :dict-code="dictKey"  placeholder="" />
                </a-form-model-item>
              </a-col>

              <!-- <a-col :span="8">
                 <a-form-model-item label="Class Site"   :wrapperCol="wrapperCol" prop="location">
                   <j-dict-select-tag type="list" v-model="model.location" dictCode="location" placeholder="" />
                 </a-form-model-item>
               </a-col>-->

              <a-col :span="8">
                <a-form-model-item label="Admission Test Score"   :wrapperCol="wrapperCol" prop="testScore">
                  <a-input-number v-model="model.testScore" placeholder="" style="width: 100%" />
                </a-form-model-item>
              </a-col>

            </a-row>
            <a-row>

              <a-col :span="8">
                <a-form-model-item label="Admission Test Date"   :wrapperCol="wrapperCol" prop="admissionTestDate">
                  <a-date-picker
                    v-model="model.admissionTestDate"
                    type="date"
                    style="width: 100%;"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="Apartment, Suite, etc."   :wrapperCol="wrapperCol" prop="houseType">
                  <a-input v-model="model.houseType" placeholder=""  ></a-input>
                </a-form-model-item>
              </a-col>

            </a-row>
            <a-row>
              <a-col :span="23">
                <a-form-model-item label="Address"   :wrapperCol="wrapperCol1" prop="address">
                  <a-input v-model="model.address" @change="handAdressChange" placeholder=""  ></a-input>
                </a-form-model-item>
              </a-col>



            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="Arrival Year"   :wrapperCol="wrapperCol" prop="arrivalYear">
                  <a-date-picker
                    format="YYYY"
                    :open="open"
                    :value = "model.arrivalYear"
                    @openChange="openYearChange"
                    @panelChange="panelYearChange"
                    @change="yearChange"
                    mode="year"
                    style="width: 100%;"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="Recommended By"   :wrapperCol="wrapperCol" prop="recommendedBy">
                  <a-input v-model="model.recommendedBy" placeholder=""  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="Parent Name"  :wrapperCol="wrapperCol" prop="parentName">
                  <a-input v-model="model.parentName" placeholder=""  ></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24">
                <a-form-model-item  :wrapperCol="wrapperCol" label="Memo">
                  <a-textarea v-model="model.memo" @change="handMemoChange" :maxLength="250" allow-clear />

                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-tab-pane>
      <!--<a-tab-pane key="tab2" tab="Transactions">
        <AccountTransactionList :student-id="formStudentId"  :disabled="disabled"></AccountTransactionList>
      </a-tab-pane>-->
    </a-tabs>

  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import AccountTransactionList from '@/views/sistersophie/account/AccountTransactionList'
import Vue from 'vue'
import {duplicateCheck} from "@api/api";

export default {
  name: 'StudentInfoForm',
  components: {
    AccountTransactionList
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    //学生ID
    studentId: {
      type:Number
    }
  },
  data () {
    return {
      dictKey:'cityList',
      open:false,
      customActiveKey:'tab1',
      model:{
        mobilePrefix:'1',
        location:'online',
      },
      form : {
        layout: 'vertical',
      },
      /*labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },*/
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      wrapperCol1: {
        xs: { span: 24 },
        sm: { span: 23 },
      },
      confirmLoading: false,
      validatorRules: {
        firstName: [
          { required: true, message: 'Please enter first name!'},
        ],
        lastName: [
          { required: true, message: 'Please enter last name!'},
        ],
        school: [
          { required: true, message: 'Please enter the school name!'},
        ],
        email: [
          {required: true, message: 'Please enter email address!'},
          { pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: 'Please enter the correct email!'},
        ],
        phone: [
          { required: false, message: 'Please enter your phone number!'},
          {
            pattern: new RegExp(/^[0-9]\d*$/, "g"),message: 'Please key in numbers!'
          },
          {
            min: 7,
            message: 'The phone number is at least 7 digits',
          }
        ],
        phonePrefix: [
          {
            required: false, message: ''
          },
          {
            pattern: new RegExp(/^[0-9]\d*$/, "g"),message: 'Please key in numbers!'
          },
          {
            min: 3,
            message: 'The prefix number is at least 3 digits',
          }
        ],
        schoolType: [
          { required: true, message: 'Please select school type!'},
        ],
        grade: [
          { required: true, message: 'Please enter grade!'},
        ],
        testScore: [
          { required: false},
          { pattern: /^-?\d+\.?\d*$/, message: 'Please key in numbers!'},
        ],
        address: [
          { required: false, message: 'Please enter the address!'},
        ],
        chineseName: [
          { required: true, message: 'Please enter the chinese name/weChat name!'},
        ],

        region: [
          { required: true, message: 'Please select a region!'},
        ],
      },
      url: {
        add: "/sistersophie/studentInfo/add",
        edit: "/sistersophie/studentInfo/edit",
        queryById: "/sistersophie/studentInfo/queryById"
      }
    }
  },
  computed: {
    formDisabled(){
      return this.disabled
    },
    formStudentId(){
      return this.studentId
    },
  },
  created () {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    handChangeRegion(val){
      console.info(val);
      this.model.region = val;
      this.dictKey = val+"List";
    },
    onPhonePrefixChange(){
      let val = this.model.phonePrefix;
      if(!val) return '';
      let len = val.length;
      console.info('len ' + len);
      if(len == 3){
        this.$refs.stPhone.focus()
      }
    },
    handMemoChange(e){
      let val = this.model.memo;
      if(!val) return '';
      val = val.toString()
      let srcValArray = val.split(' ') //按照空格分割;
      this.model.memo = this.commonChangeValToUpper(srcValArray);
    },
    handAdressChange(e){
      let val = this.model.address;
      if(!val) return '';
      val = val.toString()
      let srcValArray = val.split(' ') //按照空格分割;
      this.model.address = this.commonChangeValToUpper(srcValArray);
    },
    handSchoolChange(e){
      let val = this.model.school;
      if(!val) return '';
      val = val.toString()
      let srcValArray = val.split(' ') //按照空格分割;
      this.model.school = this.commonChangeValToUpper(srcValArray);
    },
    handFirstNameChange(e){
      let val = this.model.firstName;
      if(!val) return '';
      val = val.toString()
      let srcValArray = val.split(' ') //按照空格分割;
      this.model.firstName = this.commonChangeValToUpper(srcValArray);
    },
    handLastNameChange(e){
      let val = this.model.lastName;
      if(!val) return '';
      val = val.toString()
      let srcValArray = val.split(' ') //按照空格分割;
      this.model.lastName = this.commonChangeValToUpper(srcValArray);
    },
    commonChangeValToUpper(srcValArray){
      let temp = '';
      for(let i=0;i<srcValArray.length;i++){
        if(i == 0){
          temp = temp + this.upperVal(srcValArray[i])
        }else {
          temp = temp + ' ' + this.upperVal(srcValArray[i]);
        }
      }
      return temp;
    },
    upperVal (value) {
      if (!value) return ''
      value = value.toString()
      return value.charAt(0).toUpperCase() + value.slice(1)
    },
    onPrefixBlur() {
      const {onPrefixChange } = this;
      let value = this.model.phonePrefix ;
      let valueTemp = value ;
      if (value.charAt(value.length - 1) === '.' || value === '-') {
        onPrefixChange({ value: value.slice(0, -1) });
      }
    },
    onPrefixChange(e){
      const { value } = e.target;
      console.info(value);
      const reg = /^-?[0-9]*(\.[0-9]*)?$/;
      if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
        this.model.phonePrefix = value;
      }else{
        console.info('fail ....');
      }
    },
    openYearChange(status) {
      if (status) {
        this.open = true;
      } else {
        this.open = false;
      }
    },
    yearChange(value) {
      console.info(value);
      this.model.arrivalYear = value;
    },
    panelYearChange(value) {
      console.info(value);
      this.model.arrivalYear = value;
      this.open = false;
    },
    handleTabClick(key){
      this.customActiveKey = key
    },
    add () {
      this.edit(this.modelDefault);
    },
    edit (record) {
      this.model = Object.assign({}, record);
      if(this.model.region){
        this.dictKey = this.model.region + "List";
      }
      this.visible = true;
    },
    submitForm () {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if(!this.model.id){
            httpurl+=this.url.add;
            method = 'post';
          }else{
            httpurl+=this.url.edit;
            method = 'put';
          }
          httpAction(httpurl,this.model,method).then((res)=>{
            if(res.success){
              that.$message.success(res.message);
              that.$emit('ok');
            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }

      })
    },
  }
}
</script>